/*
 * Unidata Platform Community Edition
 * Copyright (c) 2013-2020, UNIDATA LLC, All rights reserved.
 * This file is part of the Unidata Platform Community Edition software.
 *
 * Unidata Platform Community Edition is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Unidata Platform Community Edition is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */

package org.unidata.mdm.data.service.segments.records.restore;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.unidata.mdm.core.type.calculables.CalculableHolder;
import org.unidata.mdm.core.type.data.RecordStatus;
import org.unidata.mdm.core.type.timeline.MutableTimeInterval;
import org.unidata.mdm.core.type.timeline.TimeInterval;
import org.unidata.mdm.core.type.timeline.Timeline;
import org.unidata.mdm.core.util.SecurityUtils;
import org.unidata.mdm.data.context.RestoreRecordRequestContext;
import org.unidata.mdm.data.module.DataModule;
import org.unidata.mdm.data.po.data.RecordEtalonPO;
import org.unidata.mdm.data.po.data.RecordOriginPO;
import org.unidata.mdm.data.po.data.RecordVistoryPO;
import org.unidata.mdm.data.service.RecordChangeSetProcessor;
import org.unidata.mdm.data.type.apply.RecordRestoreChangeSet;
import org.unidata.mdm.data.type.data.OriginRecord;
import org.unidata.mdm.data.type.keys.RecordKeys;
import org.unidata.mdm.system.service.PlatformConfiguration;
import org.unidata.mdm.system.type.pipeline.Point;
import org.unidata.mdm.system.type.pipeline.Start;
import org.unidata.mdm.system.type.runtime.MeasurementPoint;
import org.unidata.mdm.system.type.support.IdentityHashSet;
import org.unidata.mdm.system.util.IdUtils;

/**
 * Persists collected changes (the change set).
 * @author Mikhail Mikhailov on Nov 8, 2019
 */
@Component(RecordRestorePersistenceExecutor.SEGMENT_ID)
public class RecordRestorePersistenceExecutor extends Point<RestoreRecordRequestContext> {
    /**
     * This segment ID.
     */
    public static final String SEGMENT_ID = DataModule.MODULE_ID + "[RECORD_RESTORE_PERSISTENCE]";
    /**
     * Localized message code.
     */
    public static final String SEGMENT_DESCRIPTION = DataModule.MODULE_ID + ".record.restore.persistence.description";
    /**
     * The set processor.
     */
    @Autowired
    private RecordChangeSetProcessor recordChangeSetProcessor;
    /**
     * Platform configuration.
     */
    @Autowired
    private PlatformConfiguration platformConfiguration;
    /**
     * Constructor.
     * @param id
     * @param description
     */
    public RecordRestorePersistenceExecutor() {
        super(SEGMENT_ID, SEGMENT_DESCRIPTION);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void point(RestoreRecordRequestContext ctx) {

        MeasurementPoint.start();
        try {

            // 1. Prepare set
            prepareChangeSet(ctx);

            // 2. Apply changes
            applyChangeSet(ctx);

        } finally {
            MeasurementPoint.stop();
        }
    }

    private void applyChangeSet(RestoreRecordRequestContext ctx) {

        // Will be applied later in batched fashion.
        if (ctx.isBatchOperation()) {
            return;
        }

        RecordRestoreChangeSet set = ctx.changeSet();
        recordChangeSetProcessor.apply(set);
    }

    private void prepareChangeSet(RestoreRecordRequestContext ctx) {

        final RecordKeys keys = ctx.keys();
        final Date ts = ctx.timestamp();
        final String user = SecurityUtils.getCurrentUserName();
        final String operationId = ctx.getOperationId();
        final RecordRestoreChangeSet set = ctx.changeSet();

        final Timeline<OriginRecord> next = ctx.nextTimeline();
        Set<CalculableHolder<OriginRecord>> records = next.stream()
            .map(TimeInterval::unlock)
            .map(MutableTimeInterval::toModifications)
            .map(Map::values)
            .flatMap(Collection::stream)
            .flatMap(Collection::stream)
            .collect(Collectors.toCollection(IdentityHashSet::new));

        for (CalculableHolder<OriginRecord> ch : records) {

            OriginRecord or = ch.getValue();

            // Create vistory record and add it to the box.
            RecordVistoryPO result = new RecordVistoryPO();
            result.setShard(keys.getShard());
            result.setCreatedBy(user);
            result.setShift(or.getInfoSection().getShift());
            result.setData(or);
            result.setId(IdUtils.v1String());
            result.setOriginId(or.getInfoSection().getOriginKey().getId());
            result.setOperationId(operationId);
            result.setOperationType(or.getInfoSection().getOperationType());
            result.setMajor(platformConfiguration.getPlatformMajor());
            result.setMinor(platformConfiguration.getPlatformMinor());
            result.setValidFrom(or.getInfoSection().getValidFrom());
            result.setValidTo(or.getInfoSection().getValidTo());
            result.setCreateDate(ts);

            set.getOriginsVistoryRecordPOs().add(result);
        }

        if (!ctx.isPeriodRestore() && !ctx.isDataRestore()) {

            RecordEtalonPO update = new RecordEtalonPO();
            update.setId(keys.getEtalonKey().getId());
            update.setStatus(RecordStatus.ACTIVE);
            update.setOperationId(operationId);
            update.setShard(keys.getShard());
            update.setUpdateDate(ts);
            update.setUpdatedBy(user);

            set.setEtalonRecordUpdatePO(update);

            List<RecordOriginPO> origins = keys.getSupplementaryKeys().stream()
                .map(ok -> {
                    RecordOriginPO okpo = new RecordOriginPO();
                    okpo.setId(ok.getId());
                    okpo.setShard(keys.getShard());
                    okpo.setEtalonId(keys.getEtalonKey().getId());
                    okpo.setShard(keys.getShard());
                    okpo.setUpdateDate(ts);
                    okpo.setUpdatedBy(user);
                    okpo.setStatus(RecordStatus.ACTIVE);
                    return okpo;
                })
                .collect(Collectors.toList());

            set.getOriginRecordUpdatePOs().addAll(origins);
        }
    }
    /**
     * {@inheritDoc}
     */
    @Override
    public boolean supports(Start<?, ?> start) {
        return RestoreRecordRequestContext.class.isAssignableFrom(start.getInputTypeClass());
    }
}
